package com.eshop.controller.order;

import com.eshop.pojo.Good;
import com.eshop.pojo.Order;
import com.eshop.pojo.RespBean;
import com.eshop.service.GoodService;
import com.eshop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "前台顾客下单相关")
@RestController
@RequestMapping("/cilentOrder")
public class CilentOrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    GoodService goodService;

    @ApiOperation("客户下单")
    @PostMapping("/")
    public RespBean addOrder(@RequestBody Order order){
        if (orderService.addOrder(order) == 1){
            return RespBean.success("成功下单！");
        }
        return RespBean.error("下单失败！");
    }

    @ApiOperation("客户取消订单")
    @PutMapping("/{id}")
    public RespBean cancelOrder(@PathVariable int id){
        if (orderService.cancelOrder(id) == 1){
            return RespBean.success("订单取消成功！");
        }
        return RespBean.error("订单取消失败！");
    }

    @ApiOperation("客户确认收货")
    @PutMapping("/{id}/{gid}")
    public RespBean confirmOrder(@PathVariable int id, @PathVariable int gid){
        //确认收货，订单交易成功
        if (orderService.OrderSuccess(id) == 1){
//            Good good = goodService.queryGoodById(gid);
//            good.setGCount(good.getGCount()-1);
//            if (good.getGCount()==0)
//            {
//                goodService.recoverGood(gid);
//                goodService.removeGood(gid);
//            }
//            goodService.updateById(good);
            return RespBean.success("您已确认收货！");
        }
        else { //否则交易失败，商品重新回到库存中
            Good good = goodService.queryGoodById(gid);
            good.setGCount(good.getGCount()+1);
            if (good.getGCount()!=0 && good.getGIsSell()==1)
            {
                good.setGIsSell(0); //从售罄状态回到上架状态
            }
            goodService.updateById(good);
            return RespBean.error("确认收货失败！本次订单已失效！");
        }

    }

    @ApiOperation("删除历史订单")
    @DeleteMapping("/{id}")
    public RespBean deteleHistoryOrderById(@PathVariable int id){
        if (orderService.deteleHistoryOrderById(id) == 1){
            return RespBean.success("订单删除成功！");
        }
        return RespBean.error("订单删除失败！");
    }

//    @ApiOperation("测试")
//    @GetMapping("/hello")
//    public String hello(){
//        return "hello";
//    }
}
